package structure.proxy;

/**
 * @author lzp
 * @Date:2023/2/27
 * @description: 打印机的代理类
 */
public class PrinterProxy implements Printable {

	/**
	 * 打印机的名称
	 */
	private String name;

	/**
	 * 真正被代理的打印机对象
	 */
	private Printer real;

	public PrinterProxy(String name) {
		this.name = name;
	}

	@Override
	public void setPrinterName(String name) {
		if (real != null) {
			real.setPrinterName(name);
		}
		this.name = name;
	}

	@Override
	public String getPrinterName() {
		return name;
	}

	@Override
	public void print(String string) {
		this.realize();
		// 执行真正调用的前后 可以增强一些业务逻辑
		real.print(string);
	}

	/**
	 * 生成被代理类
	 */
	private synchronized void realize() {
		if (real == null) {
			real = new Printer(name);
		}
	}

}
